import React from 'react';
import { Row, Col, Table, Button, Divider, Form, Input, Alert, Icon, Spin, Popconfirm} from 'antd';
import {NavLink} from 'react-router-dom'
import Axios from '../../assets/js/axios'
import Utils from '../../assets/js/utils'
import {connect} from 'react-redux'
const FormItem = Form.Item;

class User extends React.Component {
    state = {
        selectedRowKeys: [], 
        data: [],
        visibility: false,
        alertInfo: {},
        loading: true
    }

    params = {
        page: 1,
        cityInfo: {}
    }

    componentWillMount() {
        this.mounted = true
        //初始化获取数据
        this.getUserList()
        if(this.mounted) {
            if(Object.keys(this.props.info).length) {
                this.setState({
                    visibility: true,
                    alertInfo: this.props.info
                })
            }
        }
    }

    //获取数据
    getUserList = (obj = {}) => {
        Axios.requestList(this,'/api/users/queryUsersByCondition', 'get',this.params, obj )
    }
    
    //点击行，多选框选中
    onRowClick = (record) => {
        const selectedRowKeys = [...this.state.selectedRowKeys];
        if (selectedRowKeys.indexOf(record.key) >= 0) {
        selectedRowKeys.splice(selectedRowKeys.indexOf(record.key), 1);
        } else {
        selectedRowKeys.push(record.key);
        }
        if(this.mounted) {
            this.setState({ selectedRowKeys });
        }
    }


    //删除行
    handleDelete = (record) => {
        Axios.ajax({
            url: '/api/users/deleteUser',
            methods: 'post',
            params:{
                id: record.id
            }
        }).then((res) => {
            if(this.mounted) {
                this.setState({
                    visibility: true,
                    alertInfo: res
                })
            }
            this.getUserList();
        })
    }

    //编辑
    handleEdit = (record) => {
        this.props.history.push(`/dashboard/user/edit/${record.id}`)
    }

    
    //查询方法
    filterUserSubmit = () => {
        this.params.cityInfo = this.cityForm.props.form.getFieldsValue();
        this.params.page = 1
        this.getUserList(this.params.cityInfo)
    }

    //查询重置方法
    filterUserReset = () => {
        this.params.page = 1
        this.getUserList()
        this.cityForm.props.form.resetFields();
    }

    onClose = (e) => {
        if(this.mounted) {
            this.setState({
                visibility: false
            })
        }
    }

    componentWillUnmount() {
        this.mounted = false
    }

    render() {
        const selectedRowKeys = this.state.selectedRowKeys;
        const rowSelection = {
                type: 'checkbox',
                selectedRowKeys,
                //使用onRow方法，点击多选框也能选中
                onChange: (selectedRowKeys, selectedRows) => {
                    this.setState({
                        selectedRowKeys,
                        selectedRows
                    })
                }
            };
            const columns = [
                {
                    title: '用户名',
                    dataIndex: 'username',
                },
                {
                    title: '手机号码',
                    dataIndex: 'phone_number',
                    width: 125
                },
                {
                    title: '邮箱',
                    dataIndex: 'email',
                    width: 180
                },
                {
                    title: '昵称',
                    dataIndex: 'nickname',
                },
                {
                    title: '备注',
                    dataIndex: 'remark',
                },
                {
                    title: '创建时间',
                    dataIndex: 'created_at',
                    width: 180,
                    render(created_at) {
                        return Utils.formateDate(created_at)
                    }
                },
                {
                    title: '修改时间',
                    dataIndex: 'updated_at',
                    width: 180,
                    render(updated_at) {
                        return Utils.formateDate(updated_at)
                    }
                },
                {
                    title: '操作',
                    key: 'action',
                    width: 150,
                    render: (text, record, index) => (
                        <div>
                            <Button size="small" onClick={() => {this.handleEdit(record)}}>编辑</Button>
                            <Divider type="vertical" />
                            <Popconfirm title="确定删除吗?" onConfirm={() => {this.handleDelete(record)}}>
                                <Button size="small"  type="primary">删除</Button>
                            </Popconfirm>
                        </div>
                    )
                }
            ]
        return (
            <div>
                {
                    this.state.visibility ? <div className="alert"><Alert {...this.state.alertInfo}></Alert> <Icon onClick={this.onClose} type="close" /> </div> : null
                }
                <Row>
                    <Col span={20}>
                        <FilterForm wrappedComponentRef={(inst) => {this.cityForm = inst;}} filterReset={() => {this.filterUserReset()}} filterSubmit={() => {this.filterUserSubmit()}}/>
                    </Col>
                    <Col span={4}>
                        <Button type="primary" style={{float: 'right'}}>
                            <NavLink to="/dashboard/user/new">新增</NavLink>
                        </Button>
                    </Col>
                </Row>
                <Row style={{marginTop: 20}}>
                    <Spin spinning={this.state.loading} tip="加载中。。。">
                        <Table bordered 
                            rowSelection={rowSelection} 
                            columns={columns} 
                            dataSource={this.state.data}
                            pagination = {this.state.totalRecord < 21 ? false : this.state.pagination}
                            locale={{emptyText: '暂无数据'}}
                            onRow = {(record, index) => {
                                return {
                                    onClick: () => {
                                        this.onRowClick(record, index)
                                    }
                                }
                            }}
                        />
                    </Spin>
                </Row>
            </div>
        );
    }
}

const mapStateToProps = state => {
    return {
        info: state.info
    }
}

export default connect(mapStateToProps)(User);

//查询列表
class  FilterForm extends React.Component {
    handleUserSubmit = () => {
        this.props.filterSubmit();
    }

    handleUserReset = () => {
        this.props.filterReset();
    }

    render() {
        const {getFieldDecorator} = this.props.form;
        return (
            <Form layout="inline">
                <FormItem label="用户名">
                    {
                        getFieldDecorator('username')(
                            <Input autoComplete="off" />
                        )
                    }
                </FormItem>
                <FormItem label="手机号码">
                    {
                        getFieldDecorator('phone_number')(
                            <Input autoComplete="off" />
                        )
                    }
                </FormItem>
                <FormItem label="邮箱">
                    {
                        getFieldDecorator('email')(
                            <Input autoComplete="off" />
                        )
                    }
                </FormItem>
                <FormItem>
                    <Button type="primary" onClick={() => {this.handleUserSubmit()}} style={{margin: '0 20px'}}>搜索</Button>
                    <Button onClick={() => {this.handleUserReset()}}>刷新</Button>
                </FormItem>
            </Form>
        )
    }
}
FilterForm = Form.create({})(FilterForm);